﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Portal.Cms.Bussiness;
using Portal.Web.Utility;
using Portal.Cms.Model;
using Portal.Utility;
using Portal.Web.Model;
using Portal.Core;
using dtSearch32Lib;
using DocumentSearchServiceModel;
using DocumentSearch32Lib;
using Portal.Systems.Model;
using Portal.Workflow.Bussiness;
using Portal.Cms.Utility;
using System.Data;
using Portal.Database.Service;
using System.Collections.ObjectModel;

namespace Portal.Cms.Render
{
    public class AddCmsSurveyDataRenderBll
    {
        static string GetPlugInJavascript(string SiteId,string ParentDataId)
        {
            string ScriptText =
                "<input type=hidden id=txtParentDataId value=\"" + ParentDataId + "\">\r\n";
            return ScriptText;
        }


        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string GroupDataId = (string)WebEnvironments.Request(SiteId, "gid");
                string ParentDataId = (string)WebEnvironments.Request(SiteId, "parent");
                string wfcId = (string)WebEnvironments.Request(SiteId, "wfc");
                if (string.IsNullOrEmpty(wfcId)) wfcId = "";
                string Html =
                   GetPlugInJavascript(SiteId, ParentDataId) +
                   DrawAddForm(SiteId, GroupDataId, wfcId).HtmlContent;
                   
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut DrawAddForm(
            string SiteId, 
            string GroupDataId,
            string wfcId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                WorkflowControlCls OWorkflowControl = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateWorkflowControlModel(SiteId, wfcId);
                WorkflowDefCls OWorkflowDef = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateWorkflowDefFromWorkflowControl(SiteId, wfcId);
                string DataLanguage = "";
                string WorkflowName = "";
                string WorkflowDefId = "";
                if (OWorkflowDef != null)
                {
                    WorkflowName = " - theo quy trình " + OWorkflowControl.Title;
                    WorkflowDefId = OWorkflowDef.WorkflowDefId;
                    DataLanguage = OWorkflowControl.DataLanguageCode;
                    //kiem tra xem role nay co quyen start quy trinh nay khong
                    bool Allow=SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckAllowAccessWorkflow(SiteId, WebSessionUtility.GetCurrentLoginUser().RoleId, WorkflowDefId);
                    if (Allow == false) throw new Exception("Bạn không có quyền thao tác với quy trình này!");
                }
                else
                {
                    SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, GroupDataPermission.StaticId, GroupDataPermission.funcAccess, GroupDataId, WebSessionUtility.GetCurrentLoginUser().UserId, true);
                }
                GroupDataCls OGroupData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateGroupDataModel(null, SiteId, GroupDataId);

                string BackScript = "javascript:window.open('SurveyInputData.aspx?gid=" + OGroupData.GroupDataId + "','_self');";
                //string UploadHandler = "CmsUploadHandler.ashx";
                
                string NewDataId = System.Guid.NewGuid().ToString();
                string Html =
                     "<script language=javascript>\r\n " +

                     " function CallSaveAddData()\r\n" +
                     " {\r\n" +
                     "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='Tiến hành cập nhật và đánh index tìm kiếm...';\r\n" +
                     "      setTimeout('RealCallSaveAddData()',10);\r\n" +
                     " }\r\n" +

                     "  function RealCallSaveAddData()\r\n" +
                     "  {\r\n" +
                     "      SiteId='" + SiteId + "';\r\n" +
                     "      GroupDataId='" + GroupDataId + "';\r\n" +
                     "      WorkflowDefId=document.getElementById('txtWorkflowDefId').value;\r\n" +
                     "      DataLanguage=document.getElementById('txtDataLanguage').value;\r\n" +
                     "      DataId=document.getElementById('txtDataId').value;\r\n"+
                     "      Alias = document.getElementById('txtAlias').value;\r\n" +
                     "      Subject = document.getElementById('txtSubject').value;\r\n" +
                     "      Description = document.getElementById('txtDescription').value; \r\n" +
                     "      SortIndex=document.getElementById('txtSortIndex').value;\r\n" +
                     "      VoteType=document.getElementById('drpSelectVoteType').value;\r\n"+
                     "      MaxAnswer=parseInt(document.getElementById('txtMaxAnswer').value);\r\n" +
                     "      AjaxOut = Portal.Cms.Render.AddCmsSurveyDataRenderBll.ServerSideCreateAnswerTextObject(SiteId, MaxAnswer).value;\r\n" +
                     "      CmsVoteAnswerItems=AjaxOut.RetObject;\r\n" +
                     "      for(var iIndex=0;iIndex<MaxAnswer;iIndex++)\r\n"+
                     "      {\r\n"+
                     "          CmsVoteAnswerItems[iIndex].Subject=document.getElementById('txtAnswerItem'+iIndex).value;\r\n" +
                     "          CmsVoteAnswerItems[iIndex].SortIndex=iIndex+1;\r\n" +
                     "      }\r\n"+
                     "      AjaxOut = Portal.Cms.Render.AddCmsSurveyDataRenderBll.ServerSideAdd(SiteId, WorkflowDefId, DataLanguage, DataId, GroupDataId, Alias, Subject, Description,  SortIndex, VoteType, CmsVoteAnswerItems).value;\r\n" +
                     "      document.getElementById('divCallSaveAddDataProcessing').innerHTML='';\r\n" +
                     "      if(AjaxOut.Error)\r\n" +
                     "      {\r\n" +
                     "          alert(AjaxOut.InfoMessage);\r\n" +
                     "          return;\r\n" +
                     "      }\r\n" +
                     "      window.open(AjaxOut.RetUrl,'_self');\r\n" +
                     "  }\r\n" +
                   "  </script>\r\n";

                //string AttachCaption = "Ảnh gắn kèm";
                string SelectVoteType = 
                    " <select id=drpSelectVoteType>\r\n" +
                    "      <option value=\"one\">Chỉ chọn 1 phương án</option>\r\n" +
                    "      <option value=\"two\">Chọn nhiều phương án</option>\r\n" +
                    "      <option value=\"text\">Nhập text</option>\r\n" +
                    "      <option value=\"level\">Chọn mức độ tốt, khá, trung bình</option>\r\n" +
                    "      <option value=\"level1\">Chọn đồng ý, không đồng ý, không ý kiến</option>\r\n" +
                    " </select>\r\n";
                
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonRoot = WebConfig.GetButtonIconRoot(OSiteParam);

                //lay xem phu trach chuyen muc nao
                string Categories = "";
                string RoleId = WebSessionUtility.GetCurrentLoginUser().RoleId;
                string ActiveDataLanguageId = "";
                if (OWorkflowControl != null)
                {
                    ActiveDataLanguageId = OWorkflowControl.DataLanguageId;
                    RoleExtraConfigCls ORoleExtraConfig = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleExtraConfigModel(SiteId, OSiteParam.SiteCode, RoleId, ActiveDataLanguageId);
                    if (ORoleExtraConfig != null)
                    {
                        Categories = ORoleExtraConfig.Categories;
                    }
                }
                int MaxAnswer = 15;
                Html +=
                   " <input id=txtWorkflowDefId type=hidden value=\"" + WorkflowDefId + "\">\r\n" +
                   " <input id=txtDataLanguage type=hidden value=\"" + DataLanguage + "\">\r\n" +
                   " <div class=DatabaseFunction>\r\n" +
                   "        <ul>\r\n" +
                   "            <li onclick=\"javascript:CallSaveAddData();\"><img class=image src=\"" + ButtonRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                   "            <li onclick=\"" + BackScript + "\"><img class=image src=\"" + ButtonRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                   "        </ul>\r\n" +
                   "  </div>\r\n" +
                   "<div class=CssFormSaveUpdate>\r\n" +
                   "  <input type=hidden id=txtDataId value=\"" + NewDataId + "\">\r\n" +
                    //"  <h3>Tạo mới " + WorkflowName + "</h3>\r\n" +
                   "  <div id=divCallSaveAddDataProcessing class=CssProcessing></div>\r\n" +
                   "  <table>\r\n" +
                   "    <tr class=\"CssRowAlias\">\r\n" +
                   "        <td class=c1>Mã:</td>\r\n" +
                   "        <td class=c2><input id=txtAlias value=\"" + System.Guid.NewGuid().ToString().Substring(0, 8) + "\" class=textbox type=textbox></td>\r\n" +
                   "    </tr>\r\n" +
                   "    <tr class=\"CssRowSubject\">\r\n" +
                   "        <td class=c1>Tiêu đề:</td>\r\n" +
                   "        <td class=c2><input id=txtSubject class=textbox type=textbox></td>\r\n" +
                   "    </tr>\r\n" +

                   "    <tr class=\"CssRowDescription\">\r\n" +
                   "        <td class=c1 style=\"vertical-align:top;\">Nội dung:</td>\r\n" +
                   "        <td class=c2>\r\n" +
                   "               <textarea type=textarea class=textarea id=\"txtDescription\" name=\"txtDescription\"></textarea>\r\n" +
                   "        </td>\r\n" +
                   "    </tr>\r\n" +


                    "    <tr>\r\n" +
                    "        <td class=c1>Loại đánh giá:</td>\r\n" +
                    "        <td class=c2>" + SelectVoteType + "</td>\r\n" +
                    "    </tr>\r\n" +

                    "    <tr class=\"CssRowSortIndex\">\r\n" +
                    "        <td class=c1>Thứ tự:</td>\r\n" +
                    "        <td class=c2><input id=txtSortIndex value=\"0\" class=textbox type=textbox></td>\r\n" +
                    "    </tr>\r\n" +

                    "    <tr class=\"CssRowListAnswer\">\r\n" +
                    "        <td class=c1></td>\r\n" +
                    "        <td class=c2>\r\n" +
                    "           <div class=\"CssSurveyAnswer\" id=\"divSurveyAnswer\">\r\n" +
                    "               <input id=\"txtMaxAnswer\" value=\""+MaxAnswer+"\" type=hidden>\r\n"+
                    "               <div id=divListAnswer>\r\n";
                for (int iIndex = 0; iIndex < MaxAnswer; iIndex++)
                {
                    Html += "<div>Phương án " + (iIndex + 1) + "</div>\r\n" +
                            "<div><textarea style=\"height:50px;\" class=textarea type=textarea id=\"txtAnswerItem"+iIndex+"\"></textarea></div>\r\n";
                }
                Html+=
                    "               </div>\r\n"+
                    "           </div>\r\n"+
                    "        </td>\r\n" +
                    "    </tr>\r\n" +

                   
                    "  </table>\r\n" +
                    "</div>\r\n";
                    
                   

                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideCreateAnswerTextObject(string SiteId, int Max)
        {
            AjaxOut OAjaxOut=new AjaxOut();
            CmsVoteAnswerItemCls[] CmsVoteAnswerItems = new CmsVoteAnswerItemCls[Max];
            for (int iIndex = 0; iIndex < CmsVoteAnswerItems.Length; iIndex++)
            {
                CmsVoteAnswerItems[iIndex] = new CmsVoteAnswerItemCls();
            }
            OAjaxOut.RetObject = CmsVoteAnswerItems;
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideAdd(
            string SiteId,
            string WorkflowDefId,
            string DataLanguage,
            string DataId,
            string GroupDataId,
            string Alias,
            string Subject,
            string Description,
            string SortIndex,
            string VoteType,
            CmsVoteAnswerItemCls[] CmsVoteAnswerItems)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                GroupDataCls OGroupData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateGroupDataModel(null, SiteId, GroupDataId);
                if (string.IsNullOrEmpty(Alias)) Alias = System.Guid.NewGuid().ToString().Substring(0, 8);
                if (string.IsNullOrEmpty(Subject)) throw new Exception("Chưa nhập tên văn bản!");
                
                IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
                IDbTransaction Trans = DBService.BeginTransaction();
                try
                {
                    CmsDataCls OCmsData = new CmsDataCls();
                    OCmsData.DataAlias = Alias;
                    OCmsData.Subject = Subject;
                    OCmsData.frkGroupDataId = GroupDataId;
                    OCmsData.Description = Description;
                    OCmsData.WorkflowDefId = WorkflowDefId;
                    try
                    {
                        OCmsData.SortIndex = int.Parse(SortIndex);
                    }
                    catch { }
                    OCmsData.VoteType = VoteType;

                    DataId = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).AddCmsData(Trans, SiteId, WorkflowDefId, DataLanguage, DataId, OCmsData, CmsVoteAnswerItems, false);
                    Trans.Commit();
                    OAjaxOut.RetUrl = "SurveyInputData.aspx?gid=" + OGroupData.GroupDataId + "&CmsDataId=" + DataId;
                }
                catch (Exception ex)
                {
                    Trans.Rollback();
                    throw (ex);
                }
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }

    }
}
